package com.blogs.ui;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blogs.component.BaseActivity;
import com.blogs.component.FavoAdapter;
import com.blogs.component.RefreshListView;
import com.blogs.component.RefreshListView.OnMoreListener;
import com.blogs.component.RefreshListView.OnRefreshListener;
import com.blogs.entity.AppEnums;
import com.blogs.entity.FavFeed;
import com.blogs.service.DeleteFarvorite;
import com.blogs.service.GetFavorite;
import com.blogs.service.GetFavorite.IMsgCallBack;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.LoadingGif;
import com.blogs.tools.TbFavorite;
import com.cnblogs.R;

public class FavoriteActivity extends BaseActivity implements OnClickListener, OnItemClickListener,
		OnItemLongClickListener {
	enum getDataMethod {
		init, // 初始化
		more, // 点击更多
		pull// 点击下拉
	}// 获取数据方式

	private DBSharedPreferences sp;
	private TextView title_include_title;
	private Button title_include_back;
	private LoadingGif loadingGif;
	private RefreshListView listView;
	private ArrayList<FavFeed> feedList;
	private LinearLayout favorite_list_body;
	private FavoAdapter adapter;
	private int currpage = 1;

	private RelativeLayout title_top_bg;
	private Toast toast;
	private ProgressDialog proDdialog;

	private TbFavorite db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorite);

		sp = new DBSharedPreferences(this);
		ViewGroup headview = (ViewGroup) findViewById(R.id.main_title_include);
		title_top_bg = (RelativeLayout) headview;
		title_include_title = (TextView) headview.findViewById(R.id.title_include_title);
		title_include_back = (Button) headview.findViewById(R.id.title_include_back);
		title_include_title.setText("收藏夹");
		title_include_back.setVisibility(View.VISIBLE);
		title_include_back.setOnClickListener(this);

		favorite_list_body = (LinearLayout) findViewById(R.id.favorite_list_body);
		listView = new RefreshListView(this);
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		listView.setonMoreListener(new OnMoreListener() {

			public void onGetMore() {
				// TODO Auto-generated method stub
				GetMoreData();
			}
		});
		loadingGif = new LoadingGif(this, listView, favorite_list_body, sp);
		listView.setonRefreshListener(new OnRefreshListener() {

			public void onRefresh() {
				// TODO Auto-generated method stub
				// 刷新
				RefreshData();
			}
		});
		loadingGif.setOnReloadListener(new LoadingGif.OnReloadListener() {

			public void onClick() {
				// TODO Auto-generated method stub
				loadingGif.showLoading();
				RefreshData();
			}
		});
		this.requestData();
		this.InitSkin();
		this.InitProDailog();
	}

	private void InitProDailog() {
		proDdialog = new ProgressDialog(this);
		proDdialog.setIndeterminate(true);
		proDdialog.setCancelable(true);
		proDdialog.setMessage("正在取消收藏...");
	}

	private void InitSkin() {
		if (sp.GetIsDarkState()) {
			title_top_bg.getBackground().setLevel(2);
			favorite_list_body.getBackground().setLevel(2);
		} else {
			title_top_bg.getBackground().setLevel(1);
			favorite_list_body.getBackground().setLevel(1);
		}
	}

	private void requestData() {
		loadingGif.showLoading();
		this.sendTimeLine("", "", getDataMethod.init);
	}

	private void RefreshData() {
		currpage = 1;
		String sinceid = feedList != null && feedList.size() != 0 ? feedList.get(0).favo_id : "";
		this.sendTimeLine(sinceid, "", getDataMethod.pull);
	}

	private void GetMoreData() {
		currpage++;
		String maxid = feedList != null && feedList.size() != 0 ? feedList.get(feedList.size() - 1).favo_id : "";
		this.sendTimeLine("", maxid, getDataMethod.more);
	}

	public void updateRequestData() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		} else {
			adapter = new FavoAdapter(this, feedList);
			listView.setAdapter(adapter);
		}
		loadingGif.showData();
		listView.onRefreshComplete();
		listView.onMoreComplete();
	}

	private void sendTimeLine(String since_id, String max_id, final getDataMethod gdm) {
		new GetFavorite(this, sp.GetSessionID(), currpage, since_id, max_id, sp.GetHasNewFavo(), new IMsgCallBack() {

			public void onSuccess(ArrayList<FavFeed> feeds) {
				// TODO Auto-generated method stub
				if (feedList == null)
					feedList = new ArrayList<FavFeed>();
				if (gdm == getDataMethod.init || gdm == getDataMethod.pull) {
					feedList.clear();
				}
				for (int i = 0; i < feeds.size(); i++) {
					feedList.add(feeds.get(i));
				}
				sp.SetHasNewFavo(false);
				updateRequestData();
			}

			public void onFailed() {
				// TODO Auto-generated method stub
				loadingGif.showFiale();
			}
		}).loadData();

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == title_include_back) {
			finish();
		}
	}

	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		// TODO Auto-generated method stub
		if (position > feedList.size())
			return;
		if (feedList.get(position - 1).blog_url.contains("http://www.cnblogs.com")) {
			Intent intent = new Intent();
			intent.setClass(this, ContentActivity.class);
			intent.putExtra("Id", feedList.get(position - 1).blog_id);
			intent.putExtra("Title", feedList.get(position - 1).title);
			intent.putExtra("Author", "收藏夹");
			intent.putExtra("publicDate", feedList.get(position - 1).favo_time);
			intent.putExtra("ViewCount", "0");
			intent.putExtra("CommentCount", "0");
			intent.putExtra("url", feedList.get(position - 1).blog_url);
			intent.putExtra("type",
					feedList.get(position - 1).blog_id.equals("0") ? AppEnums.EnumContentType.search_blog_detail
							: AppEnums.EnumContentType.blog);
			startActivity(intent);
		} else {
			// String
			// out_url="http://h2w.iask.cn/hd.php?u="+URLEncoder.encode(feedList.get(position
			// - 1).blog_url) +"&urlId="+new Date().getTime()+"&gsid=";
			String out_url = "http://h2w.iask.cn/sinaurl.php?to=&from=client&u="
					+ URLEncoder.encode(feedList.get(position - 1).blog_url) + "&urlId=" + new Date().getTime();
			Log.i("out_url", out_url);
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			Uri content_url = Uri.parse(out_url);
			intent.setData(content_url);
			startActivity(intent);
		}
	}

	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		// TODO Auto-generated method stub
		String[] items = { "查看正文", "取消收藏", "取消" };
		new AlertDialog.Builder(FavoriteActivity.this).setItems(items, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					if (feedList.get(position - 1).blog_url.contains("http://www.cnblogs.com")) {
						Intent intent_con = new Intent();
						intent_con.setClass(FavoriteActivity.this, ContentActivity.class);
						intent_con.putExtra("Id", feedList.get(position - 1).blog_id);
						intent_con.putExtra("Title", feedList.get(position - 1).title);
						intent_con.putExtra("Author", "收藏夹");
						intent_con.putExtra("publicDate", feedList.get(position - 1).favo_time);
						intent_con.putExtra("ViewCount", "0");
						intent_con.putExtra("CommentCount", "0");
						intent_con.putExtra("url", feedList.get(position - 1).blog_url);
						intent_con.putExtra("type", AppEnums.EnumContentType.blog);
						startActivity(intent_con);
					} else {
						String out_url = "http://h2w.iask.cn/sinaurl.php?to=&from=client&u="
								+ URLEncoder.encode(feedList.get(position - 1).blog_url) + "&urlId="
								+ new Date().getTime();
						Log.i("out_url", out_url);
						Intent intent = new Intent();
						intent.setAction("android.intent.action.VIEW");
						Uri content_url = Uri.parse(out_url);
						intent.setData(content_url);
						startActivity(intent);
					}
					break;
				case 1:

					new AlertDialog.Builder(FavoriteActivity.this).setTitle("取消收藏").setMessage("确定吗？")
							.setPositiveButton("是", new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									proDdialog.show();
									new DeleteFarvorite(sp.GetSessionID(), feedList.get(position - 1).favo_id,
											new DeleteFarvorite.IMsgCallBack() {

												public void onSuccess() {
													// TODO Auto-generated
													// method stub
													showToast("取消收藏成功");
													db = new TbFavorite(FavoriteActivity.this);
													db.Delete(feedList.get(position - 1).favo_id);
													db.DbClose();
													feedList.remove(position - 1);
													adapter.notifyDataSetChanged();
													proDdialog.hide();
												}

												public void onFailed(String err) {
													// TODO Auto-generated
													// method stub
													showToast("取消收藏失败," + err);
													proDdialog.hide();
												}
											}).Del();
								}
							}).setNegativeButton("否", null).show();
					break;
				case 2:

					break;
				default:
					break;
				}
			}
		}).create().show();
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		proDdialog.dismiss();
	}

	private void showToast(String text) {
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}
}
